<?php

namespace app\index\controller;

use app\admin\model\Litestorearea;
use app\common\controller\Frontend;
use app\common\model\Agency;
use app\common\model\Area;
use app\common\model\Proxylog;
use app\common\model\UserBank;
use app\common\model\UserIntegral;
use app\common\model\UserMoneyLog;
use app\common\service\LitestoreShop;
use Endroid\QrCode\QrCode;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use app\common\model\UserCollectShop;
use app\common\model\User as model_user;
use app\common\service\User as server_user;

/**
 * 会员中心
 */
class User extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['login', 'register','backpwd','merchant','receive','article'];
    protected $noNeedRight = ['*'];

    private $http_url='';
    private $site=array();

    public function _initialize()
    {
        parent::_initialize();
        $auth = $this->auth;
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->site=Config::get('site');
        $this->http_url=url('/',null,true,true);

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
    }
     /**
     * 空的请求
     */
    public function _empty($name)
    {
        $data = Hook::listen("user_request_empty", $name);
        foreach ($data as $index => $datum) {
            $this->view->assign($datum);
        }
        return $this->view->fetch('user/' . $name);
    }

    /**
     * 会员中心
     */
    public function index()
    {
        //当前用户信息
        $user=$this->auth->getUserinfo();
        //当前用户id
        $user_id=$user['id'];

        $server_user=new server_user();
        //店铺/分红金额/股权
        $data=$server_user->capital($user_id);
        //店铺状态
        $shopstatus=$data['shopstatus'];
        //分红金额
        $user_but=$data['user_but'];
        //股权
        $user_stokc=$data['user_stokc'];

        if(!empty($shopstatus)){
            $status=$shopstatus['status'];
        }else{
            $status=9999;
        }

        $this->view->assign('user_but',$user_but);
        $this->view->assign('user_stokc',$user_stokc);
        $this->view->assign('shopstatus',$status);
        $this->view->assign('users',$user);
        return $this->view->fetch();
    }

    /**
     * vip会员展示页面
     */
    public function vip(){
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 贡献值记录
     */
    public function contribution(){
        $UserMoneyLogModel=new UserMoneyLog();
        //请求页面
        $page=$this->request->get('page',1);
        //xss防攻击过滤
        $page=remove_xss($page);
        //防注入攻击
        $page=filterWords($page);
        $user_id=Cookie::get('uid');
        //判断是否ajax请求
        if($this->request->isAjax()){

            $data=$UserMoneyLogModel->getContributionList($user_id,$page);

            return json($data);
        }

        $money_type=array('8');
        $usermoney_sum=$UserMoneyLogModel->getSum($user_id,$money_type);
        $this->view->assign('http_url',$this->http_url);
        $this->view->assign('usermoney_sum',$usermoney_sum);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }
    /**
     * 我的积分
     */

    public function integral(){
        $user_id=Cookie::get('uid'); //获取用户id
        if($this->request->isAjax()){
            $UserModel=new UserIntegral();
            //页码
            $page=$this->request->get('page',1);
            //xss防攻击过滤
            $page=remove_xss($page);
            //防注入攻击
            $page=filterWords($page);
            //查询用户积分表
            $data=$UserModel->getList($user_id,$page);
            //返回josn格式
            return json($data);
        }

        $this->view->assign('http_url',$this->http_url);

        return $this->view->fetch();
    }


    /**
     * 余额记录列表
     */
    public  function balance(){
        $user_id=Cookie::get('uid'); //获取用户id
        if($this->request->isAjax()){
            $UserMoneyLogModel=new UserMoneyLog();
            //页码
            $page=$this->request->get('page',1);
            //xss防攻击过滤
            $page=remove_xss($page);
            //防注入攻击
            $page=filterWords($page);
            //查询用户余额变动记录数据
            $data=$UserMoneyLogModel->balanceList($user_id,$page);
            //返回json格式数据
            return json($data);
        }

        //获取当前登录用户信息
        $user=$this->auth->getUser();

        //获取用户余额
        $usermoney=$user['money'];

        //转换小数点
        $usermoney=round($usermoney,2);

        //小数点格式化
        if($usermoney<0){
            $usermoney=0;
        }

        $this->view->assign('mentioning',$usermoney);
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }

    /**
     * 申请提现
     */
    public function tempted(){
        //获取当前用户信息
        $user=$this->auth->getUser();
        $UserService=new server_user();
        //获取后台配置信息
        $site=$this->site;
        //判断请求是否ajax请求
        if($this->request->isAjax()){
            //用户银行卡账号id
            $id=$this->request->post('item');
            //xss攻击安全过滤
            $id=remove_xss($id);
            //注入攻击安全过滤
            $id=filterWords($id);

            //提现金额
            $money=$this->request->post('money');
            //xss攻击安全过滤
            $money=remove_xss($money);
            //注入攻击安全过滤
            $money=filterWords($money);

            /*获取提现配置来自系统配置参数--最低提现金额*/
            $cash_min=$site['cash_min'];

            if(empty($id)){
                $this->error('必须选择提现的银行账户');
            }
            $rule = [
                'money'    => 'require',
            ];

            $msg = [
                'money.require'  => '金额不能为空',
            ];
            $data = [
                'money'    => $money,
            ];
            if(empty($money)){
                $this->error('提现金额必须大于0');
            }

            $validate = new Validate($rule, $msg);
            //验证参数规则
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null);
            }

            if(!empty($cash_min)){
                if($money<=$cash_min){
                    $this->error('不能小于最低提现金额'.$cash_min.'元！');
                }
            }else{
                $this->error('暂时不能提现');
            }

            //查询用户银行信息
            $bank=UserBank::get($id);
            $data=$UserService->temptedAdd($bank,$money,$user);
            if($data['code']==1){
                //无错误返回申请成功
                $this->success('申请成功');
            }else{
                //无错误返回申请成功
                $this->error($data['msg']);
            }

        }

        //传给前端最低提现金额
        $this->view->assign('cash_min',$site['cash_min']);
        $bank=$UserService->getUserBank($user);
        //传给前端用户银行卡信息
        $this->view->assign('bank',$bank);
        //绝对url
        $this->view->assign('http_url',$this->http_url);
        //加载模板
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 银行账号
     */
    public function bankaccount(){
        $user=$this->auth->getUser();
        $UserService=new server_user();
        $bank=$UserService->getUserBank($user);
        $this->view->assign('bank',$bank);
        return $this->view->fetch();
    }

    /**
     * 底部全部订单
     */
    public function ordertotail(){
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch('orderlistnwe');
    }

    /**
     * 点击全部订单进入页面
     */
    public function orderlist(){
        //请求状态
        $statu=$this->request->get('status');
        //xss攻击安全过滤
        $statu=remove_xss($statu);
        //注入攻击安全过滤
        $status=filterWords($statu);
        if($this->request->isAjax()){
            //用户id
           $where['o.playUser_id']=Cookie::get('uid');
            //请求状态
           $status= $this->request->post('status');
            //xss攻击安全过滤
            $status=remove_xss($status);
            //注入攻击安全过滤
            $status=filterWords($status);
            if($status==1){
                //待付款
                $where['o.order_status']=array('eq','0');
            }elseif($status==2){
                //已付款
                $where['o.order_status']=array('eq','1');
            }elseif($status==3){
                //待评价
                 $where['o.comment_status']=array('eq','0');
            }
            //请求页码
            $page=$this->request->post('page',1);
            //xss攻击安全过滤
            $page=remove_xss($page);
            //注入攻击安全过滤
            $page=filterWords($page);

            $UserSerice=new server_user();

            $order=$UserSerice->orderListGet($where,$page);

            return json(array('data'=>$order));
        }
        $this->view->assign('status',$statu);
        $this->view->assign('http_url',$this->http_url);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();


    }
    /**
     * 待付款 已付款 待评价
     */
    public function order(){
        //请求状态
        $statu=$this->request->get('status');
        //xss攻击安全过滤
        $statu=remove_xss($statu);
        //注入攻击安全过滤
        $statu=filterWords($statu);

        $this->view->assign('status',$statu);

        $this->view->assign('http_url',$this->http_url);

        if($statu==1){
            $ordername='待付款';
        }elseif ($statu==2){
            $ordername='已付款';
        }elseif ($statu==3){
            $ordername='待评价';
        }
        $this->view->assign('status',$statu);
        $this->view->assign('ordername',$ordername);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();


    }

    /**
     * shop商铺评价
     */
    public function comment(){
        //商铺id
        $litestore_shop_id=$this->request->get('litestore_shop_id');
        //xss攻击安全过滤
        $litestore_shop_id=remove_xss($litestore_shop_id);
        //注入攻击安全过滤
        $litestore_shop_id=filterWords($litestore_shop_id);
        //订单id
        $litestore_shoporder_id=$this->request->get('shoporder_id');
        //xss攻击安全过滤
        $litestore_shoporder_id=remove_xss($litestore_shoporder_id);
        //注入攻击安全过滤
        $litestore_shoporder_id=filterWords($litestore_shoporder_id);

        if($this->request->isAjax()){
            //评论内容
            $content = $this->request->post('content');
            if(!empty($content)){
                //xss攻击安全过滤
                $content=remove_xss($content);
                //注入攻击安全过滤
                $content=filterWords($content);
                //清除html所有标签
                $content=clearHtml($content);
            }
            $psoce = $this->request->post('psoce');
            if(!empty($psoce)){
                //xss攻击安全过滤
                $psoce=remove_xss($psoce);
                //注入攻击安全过滤
                $psoce=filterWords($psoce);
            }
            if($psoce>5){
                $psoce=5;
            }
            $litestore_shop_id = $this->request->post('litestore_shop_id');
            $litestore_shoporder_id = $this->request->post('litestore_shoporder_id');
            $rule = [
                'psoce' => 'require',
                'content'  => 'require|length:1,200',

            ];

            $msg = [
                'content.require'  => '评价内容不能为空',
                'psoce.require'  => '评价分数必须选择',

            ];
            $data = [
                'content'   => $content,
                'psoce'   => $psoce,

            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
            }else{

                $UserService=new server_user();
                $user_id=Cookie::get('uid');
                $status=$UserService->commentGet($data,$litestore_shop_id,$litestore_shoporder_id,$user_id);
                if($status){
                    $this->success('评论成功');
                }else{
                    $this->error('评论失败');
                }

            }
        }
        $this->view->assign('litestore_shop_id',$litestore_shop_id);
        $this->view->assign('litestore_shoporder_id',$litestore_shoporder_id);
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }

    /**
     * 提现明细
     */
    public function accountdetail(){

        $where['user_id']=Cookie::get('uid');
        if($this->request->isAjax()){
            //页码
            $page=$this->request->request('page',1);

            //日期或者是开始时间
            $date=$this->request->post('date');

            //结束时间
            $endDate=$this->request->post('endDate');

            //周
            $week=$this->request->post('week');

            //月
            $monthDay=$this->request->post('monthday');

            //以前月
            $month=$this->request->post('month');

            //年
            $year=$this->request->post('year');

            //判断如传递年为空就默认当前年
            if(empty($year)){
                $year=date("Y", time()); //年
            }

            //获取指定周开始时间和结束时间
            if(!empty($week)&&!empty($year)){
                $weekArray=weekday($year,$week);
            }else{
                $weekArray=[];
            }

            //获取指定月份开始时间戳和结束时间戳
            if(!empty($year)&&!empty($monthDay)){
                $monthArray=monthday($year,$monthDay);
            }else{
                $monthArray=[];
            }

            if(!empty($date)&empty($endDate)){
                //查询日期
                $dateime=strtotime($date);//1*24*60*60
                $where['createtime']=array('between',array($dateime,($dateime+1*24*60*60-1)));//array('eq',strtotime($date));
            }elseif(!empty($date)&!empty($endDate)){
                //查询带有开始时间和结束时间
                $dateime=strtotime($date);
                $endDate=strtotime($endDate);
                $where['createtime']=array('between',array($dateime,$endDate));
            }elseif(!empty($month)){
                //查询当前月份
                if(empty($monthDay)){
                    $monthDay=date('m');
                }
                $monthArray=monthday($year,$monthDay);
                $where['createtime']=array('between',array($monthArray['start'],$monthArray['end']));
            }elseif(!empty($weekArray)){
                //查询指定周
                $where['createtime']=array('between',array($weekArray['start'],$weekArray['end']));
            }elseif(!empty($monthArray)){
                //查询指定月
                $where['createtime']=array('between',array($monthArray['start'],$monthArray['end']));
            }else{
                if(empty($monthDay)){
                    $monthDay=date('m');
                }
                $monthArray=monthday($year,$monthDay);
                $where['createtime']=array('between',array($monthArray['start'],$monthArray['end']));

            }
            $UserService=new server_user();
            $data=$UserService->accountdetailGet($where,$page);

            return json(array('data'=>$data));;

        }
        $user=$this->auth->getUser();

        $mentioning=$user['money'];
        $this->view->assign('mentioning',$mentioning);
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }

    /**
     * 提现账号管理
     * 添加账号
     */
    public function addbankaccount(){
        $UserBankModel=new UserBank();
        $id=$this->request->get('id');
        $accont=array();
        if(!empty($id)){
            $accont=$UserBankModel->where(['id'=>$id])->find();

        }
        if(empty($accont)){
            $accont=array('compellation'=>'','account'=>'','id'=>0,'branch'=>'','mobile'=>'');
        }

        if($this->request->isAjax()){
            $compellation = $this->request->post('compellation');
            $account = $this->request->post('account');
            $banking_id = $this->request->post('banking_id');
            $branch = $this->request->post('branch');
            $province = $this->request->post('province');
            $city = $this->request->post('city');
            $area = $this->request->post('area');
            $mobile = $this->request->post('mobile');
            $code = $this->request->post('code');
            $id = $this->request->post('id');

            if(!is_numeric($account)){
                $this->error('银行卡号必须是数字');
            }
            $rule = [
                'compellation'  => 'require',
                'account'  => 'require',
                'banking_id'  => 'require',
                'branch'  => 'require',
                'province'  => 'require',
                'city'  => 'require',
                'area'  => 'require',
                'mobile'  => 'require',
            ];

            $msg = [
                'compellation.require' => '姓名不能为空',
                'account.require' => '账号不能为空',
                'banking_id'  => '请选择开户行',
                'branch'  => '请输入支行',
                'province'  => '请选择省',
                'city'  => '请选择市',
                'area'  => '请选择区',
                'mobile'  => '请输入手机号',

            ];

            $data = [
                'compellation'  => $compellation,
                'account'  => $account,
                'banking_id'  => $banking_id,
                'branch'  => $branch,
                'province'  => $province,
                'city'  => $city,
                'area'  => $area,
                'mobile'  => $mobile,
            ];
            $event = 'addback';

            if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号不正确'));
            }

            $ret = \app\common\library\Sms::check($mobile, $code, $event);
            if (!$ret) {
                $this->error(__('验证码不正确，或已过期'));
            }

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }else{
                $data['user_id']=Cookie::get('uid');
                $data['status']=0;
                $data['createtime']=time();
                $data['type']=1;

                $UserBankModel->Haddbankaccount($id,$data);
                $this->success('提交成功');
            }
        }
        $banking_array=$UserBankModel->bankingListSelect();

        $this->view->assign('option', array('prov' => $this->getRegion(0)));
        $this->view->assign('banking_array',$banking_array);
        $this->view->assign('http_url',$this->http_url);
        $this->view->assign('accont',$accont);
        $this->view->assign('id',$id);
        $this->view->engine->layout('layout/merchant');

        return $this->view->fetch();
    }

    /**
     * 我的股权
     */
    public function stock(){
        $moneyModel=new UserMoneyLog();
        $page=$this->request->get('page',1);
        $where['user_id']=Cookie::get('uid');
        $where['money_type']=array('in',array('5'));

        $usermoney=$moneyModel->where($where)->page($page)->limit(12)->select();
        foreach ($usermoney as $key=>$val){
            if($val['createtime']){
                $usermoney[$key]['createtime']=datetime($val['createtime']);
            }

        }
        if($this->request->isAjax()){
            $mone_log=array();
            $mone_log['data']=$usermoney;
            $mone_log['page']=$page+1;
            return json($mone_log);
        }

        $stock=$moneyModel->where($where)->sum('money');
        $this->view->assign('mentioning',$stock);
        $this->view->assign('page',$page);
        $this->view->assign('usermoney',$usermoney);
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }
    /**
     * 我的分红
     */
    public function dividend(){
        $moneyModel=new UserMoneyLog();
        $page=$this->request->get('page',1);
        $where['user_id']=Cookie::get('uid');
        $where['money_type']=array('eq','4');

        $usermoney_sum=$moneyModel->where($where)->sum('money');
        if($this->request->isAjax()){
            $usermoney=$moneyModel->where($where)->page($page)->limit(12)->select();
            foreach ($usermoney as $key=>$val){
                if($val['createtime']){
                    $usermoney[$key]['createtime']=datetime($val['createtime']);
                }

            }
            $mone_log=array();
            $mone_log['data']=$usermoney;
            return json($mone_log);
        }
        $this->view->assign('mentioning',$usermoney_sum);
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }


    /**
     * 注册会员
     */
    public function register()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->redirect('user/index');
        if ($this->request->isAjax()) {
            $username = $this->request->post('mobile');
            $password = $this->request->post('password');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $code= $this->request->post('code');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:8,16',
                'mobile'    => 'regex:/^1\d{10}$/',
                'code'    => 'require',
                'captcha'   => 'require',
                '__token__' => 'token',
            ];

            $msg = [
                'username.require' => '手机号不能为空',
                'username.length'  => '用户名必须为3到30个字符',
                'password.require' => '密码不能为空',
                'password.length'  => '密码必须为6到30个字符',
                'captcha.require'  => '验证不能为空',
                'mobile'           => '手机不相关',
                'code.require' => '邀请码不能为空',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                'mobile'    => $mobile,
                'captcha'   => $captcha,
                'code'   => $code,
                '__token__' => $token,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }

            $event='register';
            if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号不正确'));
            }
            if ($event) {
                $userinfo = \app\common\model\User::getByMobile($mobile);
                if ($event == 'register' && $userinfo) {
                    //已被注册
                    $this->error(__('已被注册'));
                } else if (in_array($event, ['changemobile']) && $userinfo) {
                    //被占用
                    $this->error(__('已被占用'));
                } else if (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
                    //未注册
                    $this->error(__('未注册'));
                }
            }

            $ret = \app\common\library\Sms::check($mobile, $captcha, $event);

            if (!$ret) {
                $this->error(__('验证码不正确，或已过期'));
            }
            $Usercode  = \app\common\model\User::where(array('code'=>$code))->find();
            if(empty($Usercode->code)){
                $this->error(config('message.User_code_error'));
            }
            if( $Usercode->code != $code){
                $this->error(config('message.User_code_error'));
            }
            $parent_id  = $Usercode->id;


            $new_code = initcode();
            if ($this->auth->register($username, $password, $new_code, $mobile, [],$parent_id)) {

                $userServer=new \app\common\service\User();
                $userServer->getAgentId(Cookie::get('uid'));
                if(cookie('user_code')||!empty($code) ){

                    $site=$this->site;
                    $userServer->integralCreate(Cookie::get('uid'),$Usercode->id,$site);


                }
                if(cookie('cache_location_city')){

                    $area=cookie('cache_location_city');
                    $userServer->location_city_create($area,Cookie::get('uid'));

                }

                //清除携带的邀请码参数
                cookie('user_code',null);
                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }

        //是否携带邀请码参数而来
        if(cookie('user_code')){
            $this->view->assign('user_code', cookie('user_code'));
        }

        $this->view->assign('url', $url);
        $this->view->assign('http_url', $this->http_url);
        $this->view->assign('title', __('Register'));
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();

    }

    /**
     * 会员登录
     */
    public function login()
    {
        $url = $this->request->request('url');
        if ($this->auth->id)
            $this->redirect('user/index');
        if ($this->request->isAjax()) {
            $account = $this->request->post('account');
            $password = $this->request->post('password');
            $rule = [
                'account'   => 'require|length:3,11',
                'password'  => 'require|length:6,30',
            ];

            $msg = [
                'account.require'  => '帐户不能为空',
                'account.length'   => '帐户必须为3到50个字符',
                'password.require' => '密码不能为空',
                'password.length'  => '密码必须为8到16位数字加字母',
            ];
            $data = [
                'account'   => $account,
                'password'  => $password,
            ];
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }
            if ($this->auth->login($account, $password)) {

                $this->success(__('Logged in successful') ,  url('user/index'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register)/i", $referer)) {
            $url = $referer;
        }

        $this->view->assign('http_url', $this->http_url);
        $this->view->assign('url', $url);
        $this->view->assign('title', __('Login'));
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 关于我们
     */
    public function aboutus(){
        $site=$this->site;
        $aboutus=$site['aboutus'];
        $this->view->assign('aboutus',$aboutus);
        return $this->view->fetch();
    }

    /**
     * 用户协议传id=1和隐私协议隐私协议传id=2
     */
    public function article(){
        $id=$this->request->get('id');
        $article=new \app\common\model\Area();
        $article=$article->where(['id'=>$id])->find();
        $this->view->assign('article',$article);
        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    function logout()
    {
        //注销本站
        $this->auth->logout();
        $this->redirect('user/login');
    }

    /**
     * 个人信息
     */
    public function profile()
    {
        $this->view->assign('title', __('Profile'));
        return $this->view->fetch();
    }

    /**
     * 找回密码
     */
    public function backpwd()
    {
        if ($this->request->isPost()) {
            $mobile = $this->request->post("name");
            $newpassword = $this->request->post("newpassword");
            $renewpassword = $this->request->post("renewpassword");
            $captcha = $this->request->post("captcha");
            $token = $this->request->post('__token__');
            $rule = [
                'newpassword'   => 'require|length:6,30',
                'renewpassword' => 'require|length:6,30|confirm:newpassword',
                '__token__'     => 'token',
            ];

            $msg = [
            ];
            $data = [
                'newpassword'   => $newpassword,
                'renewpassword' => $renewpassword,
            ];
            $field = [
                'newpassword'   => __('New password'),
                'renewpassword' => __('Renew password')
            ];
            $ret = \app\common\library\Sms::check($mobile, $captcha, 'changepwd');

            if(!$ret) $this->error(__('验证码不正确，或已过期'));


            $validate = new Validate($rule, $msg, $field);
            $result = $validate->check($data);

            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
                return FALSE;
            }

            $ret = $this->auth->changepwd_by_mobile($mobile,$newpassword);
            if ($ret) {
                $this->success(__('Reset password successful'), url('user/login'));
            } else {
                $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
            }
        }
        $this->view->assign('title', __('Change password'));
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 设置
     */
    public function set(){
        $adress=new \app\common\model\LitestoreAdress();
        $adree_array=$adress->where(['user_id'=>Cookie::get('uid')])->count();
        if($adree_array<=0){
          $ad='请完善';

        }else{
            $ad='修改';
        }
        $UserModel=new model_user();
        $user_cout=$UserModel->where(['id'=>Cookie::get('uid')])->count();
        if($user_cout>0){
            $ad_user='修改';
        }else{
            $ad_user='请完善';
        }

        $this->view->assign('ad_user',$ad_user);
        $this->view->assign('det',$ad);
        return $this->view->fetch();
    }

    /**
     * 投诉建议
     */
    public function complaint(){
        if($this->request->isAjax()){

            $phone = $this->request->post('phone');
            $content = $this->request->post('content');
            $rule = [
                'content'  => 'require|length:1,200',
            ];

            $msg = [
                'content.require'  => '内容不能为空',
                'content.length'  => '内容长度必须为1到200位',
            ];
            $data = [
                'content'   => $content,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
                return FALSE;
            }else{

                $data['user_id']=Cookie::get('uid');
                $data['phone']=$phone;
                $data['createtime']=time();
                $complaint=new \app\common\model\UserComplaint();
                $complaint->insert($data);
                $this->success('提交成功','user/set');
            }
        }
        return $this->view->fetch();
    }
    /**
     * 个人资料修改
     */
    public function pro(){

        if($this->request->isAjax()){
            $nickname = $this->request->post('nickname');
            $token = $this->request->post('__token__');
            $rule = [
                'nickname' => 'require',
                '__token__'     => 'token',
            ];

            $msg = [
                'nickname.require'  => '昵称不能为空',
            ];
            $data = [
                'nickname'   => $nickname,
            ];

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }else{
                $UserModel=new model_user();
                $UserModel->where(['id'=>Cookie::get('uid')])->update($data);
            }
            $this->success('提交成功');
        }
        $this->view->assign('http_url',$this->http_url);

        return $this->view->fetch();
    }
    /**
     * 开通商家
     */
    public function business(){
        $user=$this->auth->getUser();
        $shop=new \app\common\model\LitestoreShop();
        if($this->request->isAjax()){
            $name=$this->request->post('name');
            $category_id=$this->request->post('category_id');
            $user_card_on=$this->request->post('user_card_on');
            $user_card_back=$this->request->post('user_card_back');
            $license=$this->request->post('license');
            $province=$this->request->post('province');
            $city=$this->request->post('city');
            $area=$this->request->post('area');
            $address=$this->request->post('address');
            $shop_image=$this->request->post('shop_image');
            $desc=$this->request->post('desc');
            $info=$this->request->post('info');
            $shop_id=$this->request->post('shop_id');
            $rule = [
                'name' => 'require',
                'user_card_on' => 'require',
                'user_card_back' => 'require',
                'license' => 'require',
                'address'    => 'require',
            ];

            $msg = [
                'name.require'  => '店名称不能为空',
                'user_card_on.require'  => '身份证正面上传',
                'user_card_back.require'  => '身份证反面上传',
                'license.require'  => '营业执照上传',
                'address.require'  => '请输入详细地址',

            ];
            $data = [
                'name'   => $name,

                'user_card_on'   => $user_card_on,
                'user_card_back'   => $user_card_back,
                'license'   => $license,

                'address'   => $address,
            ];

            $user_shop=$shop->where(['user_id'=>Cookie::get('uid')])->find();
            if(!empty($user_shop)){
                if($user_shop['status']==0){
                    $this->error('已经申请过了,正在审核中');
                }

            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {

                $this->error(__($validate->getError()));
            }else{
                if( cookie( 'cache_ip_location' )){
                    if(!empty(cookie( 'cache_ip_location' )['content'])){
                        $point=cookie( 'cache_ip_location' )['content']['point'];
                        $data['longitude']=$point['x'];
                        $data['latitude']=$point['y'];
                        $data['location']=$point['x'].','.$point['y'];
                    }
                }
                $data['info']=$info;
                $data['createtime']=time();

                $data['desc']=$desc;
                $data['shop_image']=$shop_image;
                $data['user_id']=Cookie::get('uid');
                if(empty($category_id)){
                    $this->error('行业不能为空');
                }
                if(empty($province)){
                    $this->error('省必须选择');
                }
                if(empty($city)){
                    $this->error('市必须选择');
                }
                if(empty($area)){
                    $this->error('地区必须选择');
                }
                if(empty($shop_id)){
                    $data['status']=0;
                    $data['category_id']=$category_id;
                    $data['province']= $province;
                    $data['city']   = $city;
                    $data['area']=$area;
                    $shop->insert($data);
                    $this->success('提交成功');
                }else{
                    if(!empty($category_id)){
                        $data['category_id']=$category_id;
                    }

                    if(!empty($province)){
                        $data['province']= $province;
                    }

                    if(!empty($city)){
                        $data['city']   = $city;
                    }

                    if(!empty($area)){
                        $data['area']=$area;
                    }
                    $data['status']=0;
                    $shop->where(['id'=>$shop_id])->update($data);
                    $this->success('更新成功');
                }

            }
        }

        $shopMedel=new \app\common\model\LitestoreShop();
        $shopList=$shopMedel::get(['user_id'=>$user['id']]);
        $shop=array(
            'name'=>'',
            'desc'=>'',
            'info'=>'',
            'address'=>'',
            'status'=>99999,
            'shop_image'=>'/map/images/certificate_bg.png',
            'user_card_on'=>'/map/images/certificate_bg.png',
            'user_card_back'=>'/map/images/certificate_bg.png',
            'license'=>'/map/images/certificate_bg.png',
            'id'=>0,
            'category_id'=>0,
            'province'=>0,
            'city'=>0,
            'area'=>0

        );
        if(!empty($shopList)){
            $shop['name']=$shopList->name;
            $shop['desc']=$shopList->desc;
            $shop['info']=$shopList->info;
            $shop['address']=$shopList->address;
            $shop['shop_image']=$shopList->shop_image;
            $shop['user_card_on']=$shopList->user_card_on;
            $shop['user_card_back']=$shopList->user_card_back;
            $shop['license']=$shopList->license;
            $shop['category_id']=$shopList->category_id;
            $shop['province']=$shopList->province;
            $shop['id']=$shopList->id;
            $shop['city']=$shopList->city;
            $shop['status']=$shopList->status;
            $shop['area']=$shopList->area;
        }
        $shopcategory=new \app\common\model\LitestoreShopcategory();
        $category_array=$shopcategory->select();
        $category='';
        foreach ($category_array as $key=>$val){
            if($val['id']==$shop['category_id']){
                $category .= '<option value='.$val['id'].'  selected >'.$val['name'].'</option>';
            }else{
                $category .= '<option value='.$val['id'].'   >'.$val['name'].'</option>';
            }

        }
        if(!empty($shop['id'])){
            $this->view->assign('city_id',$this->getArea($shop['city']));
            $this->view->assign('region_id',$this->getArea($shop['area']));
        }else{
            $this->view->assign('city_id','');
            $this->view->assign('region_id','');
        }
        $this->view->assign('shop',$shop);
        $this->view->assign('category',$category);
        $this->view->assign('option', array('prov' => $this->getRegion(0,false,0,false,$shop['province'])));
        $this->view->assign('http_url',$this->http_url);
        return $this->view->fetch();
    }
    /**
     * 加入代理
     */
    public function addagent(){
        $user_id=Cookie::get('uid');
        $user_server=new server_user();
        $data=$user_server->addagentServer($user_id);
        $prox=$data['prox'];
        $pro=$data['pro'];
        $this->view->assign('http_url',$this->http_url);
        $this->view->assign('prox',$prox);
        $this->view->assign('pro',$pro);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 商家管理
     */
    public  function qrcodet(){
        $shop=new LitestoreShop();
        $shopModel=new \app\common\model\LitestoreShop();
        $shopList=$shopModel->where(['user_id'=>Cookie::get('uid')])->find();

        $img=$shop->createcode($shopList['id']);
        $this->view->assign('img',$img);
        $this->view->assign('res_point',$shopList['res_point']);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 通过地区表id查询代理价格
     */
    public function AjaxSelectPrice(){

       if($this->request->isAjax()){
           $id=$this->request->get('id');
           $price=0;
           try{
               $agency_model=new Agency();
               $price_array=$agency_model->AjaxSelectPrice($id);
               $price_array=collection($price_array)->toArray();
               if(!empty($price_array)){
                   $price=$price_array[0];
               }
           }catch (\Exception $e){
               $this->error('您申请的地区价格待定，提交之后由客服人员联系您！');
           }
           $this->success('查询成功',null,$price);
       }
    }

    /**
     * 商家管理-财务管理
     */
    public function financial(){
        $UserSever=new server_user();
        $user_id=Cookie::get('uid');
        if($this->request->isAjax()){
            $page=$this->request->post('page',1);
            $type=$this->request->post('type',1);
            //日期或者是开始时间
            $date=$this->request->post('date');

            //结束时间
            $endDate=$this->request->post('endDate');

            //周
            $week=$this->request->post('week');

            //月
            $monthDay=$this->request->post('monthday');

            //年
            $year=$this->request->post('year');

            //判断如传递年为空就默认当前年
            if(empty($year)){
                $year=date("Y", time()); //年
            }

            $data=$UserSever->financialList($user_id,$type,$date,$endDate,$week,$monthDay,$year,$page);

            return json($data);

        }
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }
    /**
     * 商家管理-统计
     */
    public function tics(){
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 商家收款页面
     */
    public function merchant(){

        $UserService=new server_user();
        //获取用户信息
        $user=$this->auth->getUser();
        $user_id=$user->id;
        //获取商家id
        $shop_id=$this->request->param('shop_id');
        //获取后台系统配置信息
        $site=$this->site;
        //判断是否是支付时注册用户进行首单优惠
        if(Cookie::get('ferential')){
            if(!empty($site['preferential'])){
                $preferential= round($site['preferential'],2);
            }else{
                $preferential= 0;
            }
            $preferential_style='';
        }else{
            $preferential_style='style="display: none"';
            $preferential=0;
        }
        //获取商家信息
        $litestore_shop=\app\common\model\LitestoreShop::get($shop_id);

        //用户是否存在
        if(!$user){
            $status=1;
        }else{
            $status=0;
        }
        if($this->request->isAjax()){

            $price=$this->request->post('price1'); //支付用户输入金额
            $price=remove_xss($price);//防止xss攻击安全过滤
            $price=filterWords($price);//防止注入安全过滤

            $money=$this->request->post('money1'); //是否是用余额，如果是传用户的余额
            $money=remove_xss($money);//防止xss攻击安全过滤
            $money=filterWords($money);//防止注入安全过滤

            $preferential=$this->request->post('preferential'); //首单优惠金额
            $preferential=remove_xss($preferential);//防止xss攻击安全过滤
            $preferential=filterWords($preferential);//防止注入安全过滤

            $to_price=$this->request->post('to_price'); //实际支付金额
            $to_price=remove_xss($to_price);//防止xss攻击安全过滤
            $to_price=filterWords($to_price);//防止注入安全过滤

            //获取商家id
            $_shop_id=$this->request->post('shop_id');
            $_shop_id=remove_xss($_shop_id);//防止xss攻击安全过滤
            $_shop_id=filterWords($_shop_id);//防止注入安全过滤

            /**
             * 判断使用余额支付
             * 如果输入的金额小于余额
             * 支付金额就为0
             * 实际使用的支付余额是输入金额
             *这时订单使用的余额就是输入金额
             * *这时自己余额减去输入的金额也就是减去订单使用的余额
             */
            if($money>$price&&$to_price==0){
                $remainder=$price; //实际使用的余额是输入金额
            }else{
                $remainder=$money; //前端传入的余额
            }

            if($to_price<0){
                $this->error('支付金额必须大于或者等于0');
            }

            //生成订单号
            $order_no=date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);

            //通过商家id获取商家信息
            $shop=\app\common\model\LitestoreShop::get($_shop_id);
            //判断商家让利百分比
            if(!empty($shop->res_point)){
                //判断商家让利百分比大于100 安装100算
                if($shop->res_point>100){
                    $res_point=1;
                }else{
                    $res_point=$shop->res_point/100;
                }
            }else{
                //小于0直接赋值0
                $res_point=0;
            }

            //实际支付金额加上余额支付
            $pric_t=$to_price+$remainder;

            //判断如果是
            if($UserService->getIsParentIdShop($user_id,$shop->user_id)){
                $Payment_ph=$pric_t-($pric_t*$res_point);
            }else{
                $Payment_ph=$pric_t;
            }
            //商家订单即将插入的数据
            $status_is=$UserService->inserOrder($user_id,$order_no,$shop['id'],$shop['name'],$to_price,$preferential,$price,$shop['user_id'],$shop['category_id'],$Payment_ph,$remainder,1);

            //判断是否插入订单是否成功
            if($status_is){
                $UserService->orderPlayCompute($order_no);
                //删除首单优惠
                Cookie::delete('ferential');

                $this->success('下单成功');
            }else{
                $this->success('下单失败');
            }

        }
        $this->view->assign('shop_name',$litestore_shop['name']);
        $this->view->assign('desc',$litestore_shop['desc']);
        $this->view->assign('status',$status);
        $this->view->assign('money',$user['money']);
        $this->view->assign('parent_id',$litestore_shop['user_id']);
        $this->view->assign('preferential_style',$preferential_style);
        $this->view->assign('shop_id',$shop_id);
        $this->view->assign('register_url',url('user/receive',null,true,true));
        $this->view->assign('http_url',url('/',null,true,true));
        $this->view->assign('preferential',$preferential);
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    /**
     * 支付成功
     */
    public function sucess(){
        return $this->view->fetch();
    }

    /**
     * 未登陆进入判断如果有注册就自动登陆，如果用户就进行注册后登陆;
     */
    public function receive(){
        $UserService=new server_user();
        if($this->request->isAjax()){
            $site=$this->site;

            $username = $this->request->post('mobile');
            $password = $this->request->post('password');
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $parent_id= $this->request->post('parent_id');

            $data=array('code'=>0,'msg'=>'','type'=>0);
            $event='rev';
            if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('手机号不正确'));
            }
            if ($event) {
                $userinfo = \app\common\model\User::getByMobile($mobile);

                if ($userinfo) {
                    //已被注册
                    $user = \app\common\model\User::get(['mobile' => $mobile]);
                    if ($user) {
                        $this->auth->direct($user->id);
                        $data['msg']='你已经注册过';
                        $data['money']=$userinfo['money'];
                        $data['type']=0;
                        $data['code']=9;
                        $data['preferential']=0;

                        return json($data);
                    } else {
                        $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                    }
                } else if (!$userinfo) {
                    //未注册
                    $ret = \app\common\library\Sms::check($mobile, $captcha, $event);
                    if (!$ret) {
                        $this->error(__('验证码不正确，或已过期'));
                    }
                    $new_code = initcode();
                    if ($this->auth->register($username, $password, $new_code, $mobile, [],$parent_id)) {
                        $user=$this->auth->getUser();
                        $user_id=$user->id;
                        $UserService->integralCreate($user_id,$parent_id,$site);
                        if(cookie('cache_location_city')){
                            $area=cookie('cache_location_city');
                            $UserService->location_city_create($area,$user_id);
                        }
                        $userServer=new \app\common\service\User();
                        $userServer->getAgentId($user_id);
                        $data['msg']='注册成功';
                        $data['money']=0;
                        $data['code']=9;
                        $data['type']=1;
                        $data['preferential']=$site['preferential'];
                        Cookie::set('ferential',1);
                        return json($data);
                    } else {
                        $this->error($this->auth->getError());
                    }
                }
            }
         }
    }



    /**
     * 生成商家二维码扫描
     */
    public function playcode(){

        $user=$this->auth->getUser();
        $playUrl=url('user/merchant');
        $shop=new \app\common\model\LitestoreShop();
        $shopList=$shop->where(['user_id'=>$user['id']])->find();
        $playUrl.='?shop_id='.$shopList['id'];
        $shopList=$shop->where(['user_id'=>$user['id']])->find();
        $playUrl.='&shop_name='.$shopList['name'];
        $playUrl.='&user_id='.$user['id'];
        $playUrl.='&category_id='.$shopList['category_id'];

        if(file_exists('codes/shopcode/'.$shopList['id'].'.png')){
            return 'codes/shopcode/'.$shopList['id'].'.png';
        }else{
            $imagePath='codes/shopcode/'.$shopList['id'].'.png';
            $qrCode =  new QrCode();//创建生成二维码对象
            $qrCode->setText($playUrl)
                ->setSize(150)
                ->setPadding(10)
                ->setErrorCorrection('high')
                ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
                ->setBackgroundColor(array('r' =>225, 'g' => 225, 'b' => 225, 'a' => 0))
                ->setImageType(\Endroid\QrCode\QrCode::IMAGE_TYPE_PNG)
                ->save($imagePath);
        }

    }

    /**
      *h5加入代理
     */
    public function proxy(){
        $proxyModel=new Proxylog();
        $site=Config::get('site');
        $province='style="display: none"';
        $city=' style="display: none"';
        $area=' style="display: none"';
        $regioneIs=' style="display: none"';
        $proxy_name='';
        $number=$this->request->get('v');
        switch ($number){
            case 1:
                $province='';
                $proxy_name='省级代理';
                break;
            case 2:
                $province=' ';
                $city=' ';
                $proxy_name='市级代理';
                break;
            case 3:
                $province='';
                $city='';
                $area='';
                $proxy_name='区级代理';
                break;
            case 4:
                $province='';
                $city='';
                $area='';
                $proxy_name='个人代理';
                break;
            case 5:
                $regioneIs='';
                $proxy_name='大区代理';
                break;

        }

        if($this->request->isAjax()) {
            $number = $this->request->post('number');
            $province = $this->request->post('province');
            $city = $this->request->post('city');
            $area = $this->request->post('area');
            $regione = $this->request->post('regione');
            $price = $this->request->post('price');
            $user_id=Cookie::get('uid');

            $fullname = $this->request->post('fullname');
            $phone = $this->request->post('phone');
            $account = $this->request->post('account');
            $branch = $this->request->post('branch');
            $area_model=new Area();
            if(empty($regione)&&!empty($province)){
                $regione_array=$area_model->where(['id'=>$province])->column('regione_id');
                if(!empty($regione_array)){
                    $regione=$regione_array[0];
                }
            }
            $rule = [];
            $msg = [ ];
            $data = [];
            $status=$proxyModel->proxyIsCheck($number,$province,$city,$area,$regione,$user_id);
            if($number==1){
                $rule['province']='require';
                $msg [ 'province.require'] = '省份必须选择';
                $data['province'] = $province;
                $data['server_type']=1;
            }elseif($number==2){
                $rule['province']='require';
                $msg [ 'province.require'] = '省份必须选择';
                $data['province'] = $province;
                if(empty($city)){
                    $this->error('必须选择市');
                }
                $rule['city']='require';
                $msg['city']='市必须选择';
                $data['city']=$city;
                $data['server_type']=2;

            }elseif ($number==3||$number==4){
                $rule['province']='require';

                $msg [ 'province.require'] = '省份必须选择';
                $data['province'] = $province;
                $proxy_name='区级代理';
                if(empty($city)){
                    $this->error('必须选择市');
                }
                if(empty($area)){
                    $this->error('必须选区');
                }
                $rule['city']='require';
                $rule['area']='require';
                $msg['city']='市必须选择';
                $msg['area']='区必须选择';
                $data['city']=$city;
                $data['area']=$area;
                if($number==4){
                    $data['is_agent']=1;
                    $data['server_type']=0;
                }else{
                    $data['server_type']=3;
                }
            }elseif ($number==5){
                if(empty($regione)){
                    $this->error('必须选择大区');
                }
                $data['server_type']=5;
            }

            if($status['code']==1){
                $this->error($status['msg']);
            }

            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()));
            }else {
                $ajax = $this->request->post('ajax');
                if(!empty($ajax)){
                    $this->success('可以申请');
                }
                $UserService=new server_user();
                $status=$UserService->proxyAdd($price,$fullname,$phone,$account,$branch,$regione,$user_id);
                if($status){
                    $this->success('申请成功');
                }else{
                    $this->error('申请失败');
                }
            }
        }
        $personal_level=0;
        if($number==4){
            $personal_level=$site['personal_level'];
        }
        $personal_level=round($personal_level,2);
        $this->view->assign('personal_level',$personal_level);
        $this->view->assign('regioneIs',$regioneIs);
        $this->view->assign('regione',$this->getRegion(999999999));
        $this->view->assign('option', array('prov' => $this->getRegion(0)));
        $this->view->assign('province',$province);
        $this->view->assign('number',$number);
        $this->view->assign('proxy_name',$proxy_name);
        $this->view->assign('city',$city);
        $this->view->assign('area',$area);
        return $this->view->fetch();
    }


    /**
     * 收货地址
     */
    public  function adress(){
        $adree=new \app\common\model\LitestoreAdress();
        if($this->request->isAjax()){
            //姓名
            $name = $this->request->post('name');
            if(!empty($name)){
                //xss攻击安全过滤
                $name=remove_xss($name);
                //注入攻击安全过滤
                $name=filterWords($name);
                //清除所有html标签
                $name=clearHtml($name);
            }
            //省id
            $province_id = $this->request->post('province_id');
            if(!empty($province_id)){
                //xss攻击安全过滤
                $province_id=remove_xss($province_id);
                //注入攻击安全过滤
                $province_id=filterWords($province_id);
            }
            //市id
            $city_id = $this->request->post('city_id');
            if(!empty($city_id)){
                //xss攻击安全过滤
                $city_id=remove_xss($city_id);
                //注入攻击安全过滤
                $city_id=filterWords($city_id);
            }
            //地区id
            $region_id = $this->request->post('region_id');
            if(!empty($region_id)){
                //xss攻击安全过滤
                $region_id=remove_xss($region_id);
                //注入攻击安全过滤
                $region_id=filterWords($region_id);
            }
            //手机号
            $phone = $this->request->post('phone');
            if(!empty($phone)){
                //xss攻击安全过滤
                $phone=remove_xss($phone);
                //注入攻击安全过滤
                $phone=filterWords($phone);
                //清除所有html标签
                $phone=clearHtml($phone);
            }
            //地址详情
            $detail = $this->request->post('detail');

            if(!empty($detail)){
                //xss攻击安全过滤
                $detail=remove_xss($detail);
                //注入攻击安全过滤
                $detail=filterWords($detail);
                //清除所有html标签
                $detail=clearHtml($detail);
            }

            $token = $this->request->post('__token__');
            $rule = [
                'detail' => 'require',
                'name' => 'require',
                'province_id' => 'require',
                'city_id' => 'require',
                'region_id' => 'require',
                '__token__'     => 'token',
                'phone'    => 'regex:/^1\d{10}$/',
            ];

            $msg = [
                'name.require'  => '联系人不能为空',
                'province_id.require'  => '必须选择省',
                'city_id.require'  => '必须选择市',
                'region_id.require'  => '必须选择地区',
                'phone'=>'手机号格式不正确',
                'detail.require'  => '请输入详细地址',
            ];
            $data = [
                'name'   => $name,
                'detail'   => $detail,
                'phone'   => $phone,
                'province_id'   => $province_id,
                'region_id'   => $city_id,
                'city_id'   => $region_id,
            ];


            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);

            //验证
            if (!$result) {
                $this->error(__($validate->getError()));
            }else{
                $data['user_id']=Cookie::get('uid');

                $data['isdefault']=1;
                $adresscount=$adree->where(['user_id'=>Cookie::get('uid')])->count('user_id');
                if($adresscount>0){
                    $data['updatetime']=time();
                    $adree->where(['user_id'=>Cookie::get('uid')])->update($data);
                    $this->success('地址修改成功','user/set');
                }else{
                    $data['createtime']=time();
                    $adree->insert($data);
                    $this->success('地址添加成功','user/set');
                }

            }
        }

        $adree=$adree->where(['user_id'=>Cookie::get('uid')])->find();
        $this->view->assign('adree',$adree);
        if(!empty($adree)){
            $this->view->assign('city_id',$this->getArea($adree['city_id']));
            $this->view->assign('region_id',$this->getArea($adree['region_id']));
        }else{
            $this->view->assign('city_id','');
            $this->view->assign('region_id','');
        }


        $this->view->assign('http_url',$this->http_url);
        $this->view->assign('option', array('prov' => $this->getRegion(0,0,0,0,$adree['province_id'])));
        $this->view->engine->layout('layout/merchant');
        return $this->view->fetch();
    }

    public function getRegion($pid = 0, $ajax = false, $checked = 0, $prvcheck = false,$index=0)
    {
        $areaModel=new Litestorearea();
        $r = $areaModel->where("pid=" . $pid)->select();  //Region省市级联表，parentid父亲级id，pid自增id
        return $this::getSelectOption($r, 'id', 'name',$index);

    }
    public function  getArea($id){
        $areaModel=new Litestorearea();
        $area=$areaModel->where("id=" . $id)->find();
        if(!empty($area)){
           $option= '<option value='.$area['id'].'>'.$area['name'].'</option>';
        }else{
            $option='0';
        }
        return  $option;
    }

    /**
     * 我的收藏列表
     */
    public function collectshop()
    {

        if($this->request->isAjax()){
            $UserCollectShop = new UserCollectShop();
            $data =$UserCollectShop->user_collect_shop(Cookie::get('uid'));
            foreach ($data as $k=>$v){
                @$data[$k]['length'] = web_getDistance($this->location['content']['point']['x'],$this->location['content']['point']['y'],$v['longitude'],$v['latitude']);
            }
            if(!$data) {
                echo 0;exit;
            }
            $this->assign('data',$data);
            return $this->fetch('shop/shoplist_ajax');
            exit;
        }
        $this->view->engine->layout('layout/merchant');
        return $this->fetch();

    }

    /**
     * @return mixed
     * 我的推广二维码
     */
    public function mycode()
    {

        $user=$this->auth->getUserinfo();
        $this->assign('user',$user);

        $code_url = url('/index/index/index',array('code'=>$user['code']),true,true);
        $server_user = new server_user();
        $path = $server_user->createcode($user['code']);

        $this->assign('path',$path);
        $this->assign('code_url',$code_url);

        $this->view->engine->layout('layout/merchant');
        return $this->fetch();
    }

    /**
     * @return mixed
     * 我的子用户
     */
    public function myteamusers()
    {
        $model_user = new model_user();
        $list = $model_user->myteamusers(input('live/d',1),Cookie::get('uid'));
        if(!$list) {
            echo 0;
            exit;
        }
        $this->assign('list',$list);
        $this->view->engine->layout('layout/newdefault');
        return $this->fetch();
    }

    /**
     * 查询会员自己一级会员
     */
    public function selectsers(){
        //请求会员id
        $parent_user_id= $this->request->request('parent_user_id');
        //xss攻击安全过滤
        $parent_user_id=remove_xss($parent_user_id);
        //注入安全过滤
        $parent_user_id=filterWords($parent_user_id);

        $model_user = new model_user();
        if($this->request->isAjax()){
            //请求类型:1=已经会员,2=二级会员
            $live= $this->request->request('live');
            //xss攻击安全过滤
            $live=remove_xss($live);
            //注入安全过滤
            $live=filterWords($live);
            //请求会员id
            $parent_user_id= $this->request->request('parent_user_id');
            //xss攻击安全过滤
            $parent_user_id=remove_xss($parent_user_id);
            //注入安全过滤
            $parent_user_id=filterWords($parent_user_id);
            //请求页码
            $page=$this->request->request('offset');
            //xss攻击安全过滤
            $page=remove_xss($page);
            //注入安全过滤
            $page=filterWords($page);
            //请求加载一页多少条,默认10条
            $number = $this->request->request('limit');
            //xss攻击安全过滤
            $number=remove_xss($number);
            //注入安全过滤
            $number=filterWords($number);

            $limit = $number?$number:10;
            $user=$this->auth->getUser();
            $uid=$user->id;
            if($live==1){
                $data=$model_user->myteamusersnews($live,$uid,$page,$limit);
            }elseif ($live==2){
                $data=$model_user->myteamusersnews($live,$parent_user_id,$page,$limit);
            }else{
                $data=[];
            }

            if(empty($data['data'])){
                $this->error('暂无数据','',$data);
            }else{
                $this->success('请求成功','',$data);
            }

        }
        $this->assign('parent_user_id',$parent_user_id);
        $this->view->engine->layout('layout/merchant');
        return $this->fetch();
    }

    /**
     * @return mixed
     * 加入代理
     */
    public function join_vip()
    {

        $user=$this->auth->getUserinfo();
        if($user['is_vip'] == 1) $this->redirect('user/index');

        if($this->request->isAjax()){
            $model_user = new model_user();
            $res = $model_user->join_vip(Cookie::get('uid'));
            if($res){
                $this->success('模拟：开通成功');
            }else{
                $this->error('操作失败，请重试');
            }
            exit;
        }
        $this->view->engine->layout('layout/merchant');

        return $this->fetch();
    }

}
